﻿using AutoMapper;
using FlyingHat.Common.Extensions;
using FlyingHat.Core.Entities;
using FlyingHat.Model.Models;
using FlyingHat.Model.Models.Global;
using FlyingHat.Repository.IRepository;
using FlyingHat.Service.IService;
using Microsoft.Extensions.Logging;

namespace FlyingHat.Service.Service
{
    public class LibraryService : ILibraryService
    {
        private readonly ILibraryRepository libraryRepository;
        private readonly IBookshelfRepository bookshelfRepository;
        private readonly IMapper mapper;
        private readonly ILogger<LibraryService> logger;

        public LibraryService(ILibraryRepository libraryRepository, IMapper mapper, IBookshelfRepository bookshelfRepository, ILogger<LibraryService> logger)
        {
            this.libraryRepository = libraryRepository;
            this.mapper = mapper;
            this.bookshelfRepository = bookshelfRepository;
            this.logger = logger;
        }

        public async Task<IReturnModel> GetList(string? name, int page, int limit)
        {
            var list = await libraryRepository.GetAllAsync();
            if (!string.IsNullOrWhiteSpace(name))
            {
                list = list.Where(i => i.Name.Contains(name));
            }
            var count = list.Count();
            if (count == 0)
            {
                return ReturnModel.Page();
            }
            var res = list.OrderBy(i => i.Code).Skip((page - 1) * limit).Take(limit).ToList();
            return ReturnModel.Page(count, res);
        }

        public async Task<IReturnModel> AddOrUpdate(ModifyLibraryModel model)
        {

            bool flag = await libraryRepository.ExistAsync(i => i.Id != model.Id && i.Code == model.Code).ConfigureAwait(false);
            if (flag)
            {
                return ReturnModel.Fail("图书室编号已存在");
            }
            var entity = mapper.Map<Library>(model);
            if (model.Id > 0)
            {
                flag = await libraryRepository.UpdateAsync(entity).ConfigureAwait(false);
            }
            else
            {
                model.Id = await libraryRepository.AddReturnIdAsync(entity).ConfigureAwait(false);
                flag = model.Id > 0;
            }
            // 处理书架
            if (model.Bookshelfs.Count > 0)
            {
                var shelf = mapper.Map<List<Bookshelf>>(model.Bookshelfs);
                shelf.ForEach(i => { i.LibraryId = model.Id; });
                var rows = await bookshelfRepository.AddRangeAsync(shelf).ConfigureAwait(false);
                flag = rows > 0;
            }
            if (flag && model.DeleteShelfId.Count > 0)
            {
                flag = await bookshelfRepository.DeleteAsync(model.DeleteShelfId).ConfigureAwait(false);
            }
            return ReturnModel.Result(flag, "保存");
        }

        public async Task<IReturnModel> Delete(long id)
        {
            using var tran = await libraryRepository.BeginTransactionAsync().ConfigureAwait(false);
            try
            {
                var flag = await libraryRepository.DeleteAsync(id).ConfigureAwait(false);
                if (flag)
                {
                    flag = await bookshelfRepository.DeleteAsync(i => i.LibraryId == id).ConfigureAwait(false);
                    await libraryRepository.CommitTransactionAsync().ConfigureAwait(false);
                }
                return ReturnModel.Result(flag, "删除");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除图书室出现异常");
                await libraryRepository.RollbackTransactionAsync().ConfigureAwait(false);
                return ReturnModel.Fail("删除失败");
            }
        }

        public async Task<List<SelectModel>> GetSelect()
        {
            var list = await libraryRepository.GetListAsync();
            return list.Select(i => new SelectModel { Text = $"{i.Code}-{i.Name}", Value = i.Id.ToString() }).ToList();
        }
    }
}
